package cn.gqr.service.Impl;

import cn.gqr.entity.Hot;
import cn.gqr.entity.Largefile;
import cn.gqr.mapper.HotMapper;
import cn.gqr.service.HotService;
import cn.gqr.service.TypeService;
import cn.gqr.tool.RespJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class HotServiceImpl implements HotService {

    @Autowired
    HotMapper hotMapper;


    @Override
    public List<Hot> findAll() {
        return hotMapper.findAll();
    }

    @Override
    public int delete(int id) {
        return hotMapper.delete(id);
    }

    @Override
    @Transactional
    public Map<String,Object> addHot(Hot hot, MultipartFile file, Largefile largefile) {
        //图片未上传
        if(file == null){
            return RespJson.pack(500,"图片未上传",null);
        }
        //图片上传
        String uuid = filesUpload(largefile, file);
        //设置hot对象的图片的uuid
        hot.setPicture(uuid);
        return RespJson.pack(200,"添加成功",findById(hot.getId()));
    }


    @Override
    public int delPic(String uuid) {
        return hotMapper.delPic(uuid);
    }

    @Override
    public Largefile findByPicture(String picture) {
        return hotMapper.findByPicture(picture);
    }

    @Override
    public String filesUpload(Largefile largefile, MultipartFile file) {
        //生成uuid
        String newName = (UUID.randomUUID().toString()).replace("-","");	//获取UUID并转化为String对象
        //设置uuid
        largefile.setId(newName);
        //设置文件名称
        largefile.setFilename(file.getOriginalFilename());
        //转换byte
        byte[] buf = null;
        try {
            buf = file.getBytes();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //设置图片内容
        largefile.setContent(buf);
        //添加图片
        hotMapper.addPicture(largefile);
        return newName;
    }

    @Override
    public Hot findById(int id) {
        return hotMapper.findById(id);
    }
}
